import React, { Component } from 'react';
import ReactDom from 'react-dom';
import util from "@/common/util";
import layer from "@/common/layer";
import cakeflakes from "@/common/cakeflakes";
import axios from 'axios';
import ReactSwiper from 'reactjs-swiper';
import jquery from 'jquery';


class Crabactivity extends Component {
    constructor(props) {
        super(props);
        this.state = {
            prizeList: [],
            image: '/assets/wechat/btn_active.png',
            activitytime: '',
            toggleimg: "none"
        }
    }

    async sendcode() {
        var wechatcode = util.getQuery().code;
        let res = await util.rjax({
            url: '/wxAuthenticate/getOpenId?code=' + wechatcode,
            type: 'post',
        }).catch((res) => {
            console.log("catch:" + res)
        })
        if (res) {
            console.log("if(res):" + res)
            sessionStorage.setItem("openid", res.data.openId)
        }
    }

    componentDidMount() {
        if (util.getQuery().code) {
            var openid = sessionStorage.getItem("openid")
            if (!openid || openid === 'null') {
                this.sendcode()
            }
        }
        else {
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxeaccffdd3826280c&redirect_uri=http%3a%2f%2fwww.rongsue.com%2fwechat%2fcrabactivity.html&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect`
        }

        let getconfig = async function () {
            let res = await util.rjax({
                url: "/wx/getwx?url=" + encodeURIComponent(window.location.href.split('#')[0]),
                type: "POST"
            })
            if (res) {
                wx.config({
                    debug: false,
                    appId: 'wxeaccffdd3826280c', // 必填，公众号的唯一标识
                    timestamp: parseInt(res.data.timestamp),// 必填，生成签名的时间戳
                    nonceStr: res.data.nonceStr,// 必填，生成签名的随机串
                    signature: res.data.signature,// 必填，签名
                    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']// 必填，需要使用的JS接口列表
                })
            }
        }
        getconfig()

        // var that = this
        wx.ready(function () {
            //朋友圈
            wx.onMenuShareTimeline({// 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口（即将废弃）
                title: '苏e融喜迎国庆！助力夺大奖！', // 分享标题
                link: 'http://www.rongsue.com/wechat/crabactivity.html', // 分享链接
                imgUrl: 'http://img0.rongsue.com/FoCM38f9Tm0cNkvg8NasnlmGqEsh',
                success: function (res) {
                    // that.setState({ share: true })
                    // alert("分享成功")
                },
                cancel: function (res) {
                    // alert("取消了分享")
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });

            //朋友
            wx.onMenuShareAppMessage({//获取“分享给朋友”按钮点击状态及自定义分享内容接口（即将废弃）
                title: '苏e融喜迎国庆！助力夺大奖！', // 分享标题
                desc: '“Disney黄金双挂坠项链、阳澄湖大闸蟹、九阳多功能家电烤箱、车载净化器....”', // 分享描述
                link: 'http://www.rongsue.com/wechat/crabactivity.html', // 分享链接
                imgUrl: 'http://img0.rongsue.com/FoCM38f9Tm0cNkvg8NasnlmGqEsh', // 分享图标
                type: '', // 分享类型,music、video或link，不填默认为link
                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                    // that.setState({ share: true })
                    // alert("分享成功")
                },
                cancel: function () {
                    // alert("取消了分享")
                    // 用户取消分享后执行的回调函数
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        });

        this.getPrizelist()

        jquery("#crab").on("click", ".crabcard", function () {
            let val = jquery(this).find('.btnwrite').html()
            if (val === "助力免费拿") {
                var proid = jquery(this).data("id");
                window.location.href = './crabdetail.html?id=' + proid;
            } if (val === "奖品发完了") {
                layer.open({
                    content: "奖品发完了,看看其他产品吧",
                    btn: "好的"
                })
            } else {
                layer.open({
                    content: "活动尚未开始",
                    btn: "好的"
                })
            }
        });

        jquery('.rule').click(function () {
            jquery(".dialog").css('display', 'block')
        })
        jquery('.ruleclose').click(function () {
            jquery(".dialog").css('display', 'none')
        })

        var timebool = this.checkTime('2018-09-26', '2018-09-30');//注意：日期用“-”分隔
        if (timebool == 1) {
            this.setState({ activitytime: '活动还未开始' })
            this.setState({ image: '/assets/wechat/btn_disabled.png' })
        } else if (timebool == 2) {//活动已结束
            this.setState({ activitytime: '活动已结束' })
            this.setState({ image: '/assets/wechat/btn_disabled.png' })
            this.setState({ toggleimg: 'block' })
        }
        else if (timebool == 3) {
            var nowTime = new Date();
            var time = nowTime.getFullYear() + "-" + (nowTime.getMonth() + 1) + "-" + nowTime.getDate();
            if (time === '2018-9-28') {
                this.startSell(10, 2)
                this.startSell(14, 3)
                this.startSell(37, 4)
                this.startSell(58, 5)
                this.startSell(62, 6)
            } else if (time === '2018-9-29') {
                this.startSell(0, 2)
                this.startSell(0, 3)
                this.startSell(13, 4)
                this.startSell(34, 5)
                this.startSell(38, 6)
            } else if (time === '2018-9-30') {
                this.startSell(0, 2)
                this.startSell(0, 3)
                this.startSell(0, 4)
                this.startSell(10, 5)
                this.startSell(14, 6)
            }

        }
    }

    async getPrizelist() {
        let res = await util.rjax({
            url: '/prize/list/1',//type=1 助力产品 type=2  抽奖产品
            type: 'get',
        })
        this.setState({ prizeList: res.data });
        for (let i in res.data) {
            if (res.data[i].count - res.data[i].total >= 0) {
                jquery('.crabcard').eq(i).find('.btnwrite').html('奖品发完了')
                jquery('.crabcard').eq(i).find('.btncall').attr('src', '/assets/wechat/btn_disabled.png')
            }
        }
    }

    startSell(stime, i) {//stime 截止时间 i 第几个.crabcard
        var nowTime = new Date(); //当前时间
        var endTime = new Date(nowTime.getFullYear(), nowTime.getMonth(), nowTime.getDate(), stime, 0, 0); //到当天的12点
        var resultTime = Math.floor(endTime - nowTime) / 1000;  //两个时间相减,得到的是毫秒ms,变成秒
        var intervalStartSell = '';
        clearInterval(intervalStartSell);
        intervalStartSell = setInterval(function () { //倒计时
            if (resultTime > 1) {
                resultTime = resultTime - 1;
                var second = Math.floor(resultTime % 60);
                var minite = Math.floor((resultTime / 60) % 60);
                var hour = Math.floor((resultTime / 3600) % 72);
                second = second < 10 ? ("0" + second) : second;
                minite = minite < 10 ? ("0" + minite) : minite;
                hour = hour < 10 ? ("0" + hour) : hour;
                var re = hour + ":" + minite + ":" + second;
                jquery(".crabcard:nth-child(" + i + ") .btncall").attr("src", '/assets/wechat/btn_disabled.png');
                jquery(".crabcard:nth-child(" + i + ") .btnwrite").html('距活动开始：' + hour + ":" + minite + ":" + second);

            } else if (resultTime < 0) {
                clearInterval(intervalStartSell);
                var val = jquery(".crabcard:nth-child(" + i + ") .surplusnum i").html()
                if (val === '0份') {
                    jquery(".crabcard:nth-child(" + i + ") .btncall").attr("src", '/assets/wechat/btn_disabled.png');
                    jquery(".crabcard:nth-child(" + i + ") .btnwrite").html("奖品发完了");
                } else {
                    jquery(".crabcard:nth-child(" + i + ") .btncall").attr("src", '/assets/wechat/btn_active.png');
                    jquery(".crabcard:nth-child(" + i + ") .btnwrite").html("助力免费拿");
                }
            }
        }, 1000);
    }

    checkTime(stime, etime) {
        //开始时间
        var arrs = stime.split("-");
        var startTime = new Date(arrs[0], arrs[1], arrs[2]);
        var startTimes = startTime.getTime();
        //结束时间
        var arre = etime.split("-");
        var endTime = new Date(arre[0], arre[1], arre[2]);
        var endTimes = endTime.getTime();
        //当前时间
        var thisDate = new Date();
        var thisDates = thisDate.getFullYear() + "-0" + (thisDate.getMonth() + 1) + "-" + thisDate.getDate();
        var arrn = thisDates.split("-");
        var nowTime = new Date(arrn[0], arrn[1], arrn[2]);
        var nowTimes = nowTime.getTime();

        if (nowTimes < startTimes) {
            return 1;
        } else if (nowTimes > endTimes) {
            return 2;
        } else {
            return 3;
        }
    }

    render() {
        let loans = this.state.prizeList.map((item, index) => {
            return (
                <div className="crabcard" data-id={item.id} key={index}>
                    <div style={{ position: 'relative' }}>
                        <img className="crabpic" src={item.image} alt="" />
                        {/* <p className="crabprice">商品市场价值{item.price}元</p> */}
                    </div>
                    <p className="crabintr">{item.introduction}</p>
                    <p className="guys">要求：需{item.assistCount}个好友助力，先到先得</p>
                    <p className="crabnum">
                        <span>数量：<i>{item.total}份</i></span>
                        <b></b>
                        <span className="surplusnum">剩余：<i>{item.total - item.count}份</i></span>
                    </p>
                    <div className="btnbox" style={{ position: 'relative' }}>
                        <img className="btncall" src={this.state.image} alt="" />
                        <p className="btnwrite" data-id={item.id}>{this.state.activitytime}</p>
                    </div>
                    <a href={"./crabprogress.html?id=" + item.id}>
                        <button className="progress">助力进度</button>
                    </a>
                    <img style={{ "display": this.state.toggleimg }} className="finishimg" src="/assets/wechat/crabfinish.png" alt="" />
                </div>
            )
        })

        return (
            <div>
                <div id="crab">
                    <div className='crabtop'>
                        <img className="toppic" src="/assets/wechat/crabtop_pic.png" alt="" />
                        <span className="rule"><i></i>规则</span>
                    </div>
                    {loans}
                </div>

                <div className="dialog">
                    <img className="rulebg" src="/assets/wechat/rulebg.png" alt="" />
                    <img className="ruleclose" src="/assets/wechat/ruleclose.png" alt="" />
                    <h4>· 活动规则 ·</h4>
                    <div className="rule">
                        <p>1. 9.28-9.30日苏e融活动期间每天不同时段开启奖品发放，共有五种奖品，数量有限，先到先得！</p>
                        <p>2. 选择你想获得的奖品，通过让好友助力的方式获得。</p>
                        <p>3. 不同时段活动开启后未能助力满人数的奖品，可继续助力直至奖品发放完毕以及活动结束为止。</p>
                        <p>4. 为了保证活动的公平、公正、公开原则，禁止盗刷，违者取消获奖资格。</p>
                        <p className="rulerequ"> 领奖须知：
                         获得奖品者填写个人信息进行领奖后，需分享至朋友圈凭获奖截图及朋友圈截图进行领奖。奖品在活动结束5-7个工作日后进行发放</p>
                    </div>
                </div>
            </div >
        )
    }
}
ReactDom.render(<Crabactivity />, document.getElementById("app"));